from django import forms
from .models import Tool, ToolCategory

class ToolForm(forms.ModelForm):
    """工具创建和编辑表单"""
    
    class Meta:
        model = Tool
        fields = [
            'name', 'category', 'description', 'url', 'icon', 
            'screenshot', 'tool_type', 'is_featured', 'is_free'
        ]
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '输入工具名称'
            }),
            'category': forms.Select(attrs={
                'class': 'form-select'
            }),
            'description': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 4,
                'placeholder': '描述工具的功能和特点'
            }),
            'url': forms.URLInput(attrs={
                'class': 'form-control',
                'placeholder': 'https://example.com'
            }),
            'icon': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'fas fa-tools'
            }),
            'screenshot': forms.FileInput(attrs={
                'class': 'form-control',
                'accept': 'image/*'
            }),
            'tool_type': forms.Select(attrs={
                'class': 'form-select'
            }),
            'is_featured': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            }),
            'is_free': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            }),
        }
        labels = {
            'name': '工具名称',
            'category': '分类',
            'description': '工具描述',
            'url': '工具链接',
            'icon': '图标类名',
            'screenshot': '截图',
            'tool_type': '工具类型',
            'is_featured': '推荐工具',
            'is_free': '免费工具',
        }
        help_texts = {
            'icon': '使用FontAwesome图标类名，如：fas fa-tools',
            'url': '请输入完整的URL地址',
            'screenshot': '上传工具截图（可选）',
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 设置分类选择框的空选项
        self.fields['category'].empty_label = "选择分类"
        
    def clean_url(self):
        """验证URL格式"""
        url = self.cleaned_data.get('url')
        if url and not url.startswith(('http://', 'https://')):
            raise forms.ValidationError('请输入完整的URL地址（包含http://或https://）')
        return url